package com.wyz.saas.common.utils

import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

object HashUtil {
    private val HEX_DIGITS = charArrayOf(
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'a', 'b', 'c', 'd', 'e', 'f'
    )

    private fun convertToHexString(b: ByteArray): String? {
        val sb = StringBuilder(b.size * 2)
        for (a in b) {
            sb.append(HEX_DIGITS[a.toInt() and 0xf0 ushr 4])
            sb.append(HEX_DIGITS[a.toInt() and 0x0f])
        }
        return sb.toString()
    }

    /**
     * Get a String's HashCode
     *
     * @param str String
     * @return HashCode
     */
    fun getMD5String(str: String): String? {
        val md5: MessageDigest = try {
            MessageDigest.getInstance("MD5")
        } catch (e: NoSuchAlgorithmException) {
            return null
        }
        md5.update(str.toByteArray())
        return convertToHexString(md5.digest())
    }

    /**
     * Get a File's HashCode
     *
     * @param file File
     * @return HashCode
     */
    fun getMD5String(file: File): String? {
        // Create md5
        val md5: MessageDigest = try {
            MessageDigest.getInstance("MD5")
        } catch (e: NoSuchAlgorithmException) {
            return null
        }
        // Stream
        var `in`: InputStream? = null
        val buffer = ByteArray(1024)
        var numRead: Int
        // Read
        return try {
            `in` = FileInputStream(file)
            while (`in`.read(buffer).also { numRead = it } > 0) {
                md5.update(buffer, 0, numRead)
            }
            convertToHexString(md5.digest())
        } catch (e: Exception) {
            null
        } finally {
            if (`in` != null) {
                try {
                    `in`.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }
}